package com.demo.common.base.util;

import com.demo.common.base.exception.BaseException;
import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * 对象操作类
 *
 * @author DayDayUp
 * @datetime 2023-09-12 15:23
 **/
@Slf4j
public class ObjectUtil {
    /**
     * 将Object对象转byte数组
     * @param obj byte数组的object对象
     * @return byte[]
     */
    public static byte[] object2ByteArray(Object obj) {
        byte[] bytes;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(obj);
            oos.flush();
            bytes = bos.toByteArray();
            oos.close();
            bos.close();
        } catch (IOException ex) {
            log.error("对象转byte[]失败",ex);
            throw new BaseException("对象转byte[]失败");
        }
        return bytes;
    }

}
